﻿package com.neriksworkshop.colourLoversDemos.colourExplore.data 
{
	import com.neriksworkshop.lib.colourLovers.items.Color;
	import com.neriksworkshop.lib.colourLovers.items.Palette;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	/**
	 * ...
	 * @author Erik
	 */
	public class ColourNeighbourhood extends EventDispatcher
	{
		
		private var _baseColour:Colour;
		private var _index:int; 
		
		private var cn:Object = { rgb:[], ind:0, pol:1, incr:1, it:0 }; 
		
		private var _palettes:Array = new Array();

		public var currentReqId:int;
		
		
		public function ColourNeighbourhood(_baseColour:Colour, _index:int) 
		{
			this._baseColour = _baseColour;
			this._index = _index;
			
			//trace('base:' + _baseColour.rgb, _baseColour.hexStr);
		
		}
		
		
		public function getNextNeighbourHex():String
		{
			for (var i:int = 0; i < 3; i++) 
			{
				if (i == cn.ind)	cn.rgb[i] = _baseColour.rgb[i] + (cn.incr * cn.pol);
				else				cn.rgb[i] = _baseColour.rgb[i];
			}
						
			if (cn.pol == -1 && cn.ind == 2) cn.incr++;
			if (cn.ind == 2) cn.pol = -cn.pol;			
			if (cn.ind < 2) cn.ind++ else cn.ind = 0;
			
			
			
			if (cn.rgb[0] < 0 || cn.rgb[1] < 0 || cn.rgb[2] < 0 || cn.rgb[0] > 0xFF || cn.rgb[1] > 0xFF || cn.rgb[2] > 0xFF) return getNextNeighbourHex();
			else { return Colour.hexToHexStr(Colour.rgbToHex(cn.rgb)) };
			
		}
		
		public function addPalettes(pals:Array, originalColorHex:String):void
		{
			//trace(_baseColour, originalColorHex)
			//if (_palettes.length == 0) dispatchEvent(new Event("paletteNeighbourhoodReady"));
			
			for each (var pal:Palette in pals) 
			{
				_palettes.push({palette:pal, newPaletteIndex:pal.getColorIndexInPalette(originalColorHex)});
			}
		}
		

		
		public function getHighestRankedPalette():Object
		{
			var bestPal:Object = _palettes[0];
			var bestIndex:int = 0;
			
			for (var i:int = 0; i < _palettes.length; i++) 
			{
				if (bestPal.palette.rank > _palettes[i].palette.rank) 
				{
					bestPal = _palettes[i];
					bestIndex = i;
				}
			}
			
			_palettes.splice(bestIndex, 1);
			
			return bestPal;
		}
		
		public function get nbPalettes():int
		{
			return _palettes.length;
		}
		
		public function get index():int { return _index; }
		
		
		
	}
	
}